package com.sd365.gateway.authentication.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sd365.common.util.TokenUtil;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author LaiRuiQing
 * @version 1.0
 * @ClassName JwtUtil
 * @Description 生成jwt token 工具类
 * @date 2023/03/08/10:00
 */
public class JwtUtil {

    /**
     * jwt 的header 和 payLoad
     */
    private static JSONObject header = new JSONObject();
    private static JSONObject playLoad = new JSONObject();

    private static final Long PERIOD = 86400000L;

    /**
     * 密钥
     */
    private static String PRIVATE_KEY = "hello word!";

    public static String build(String code, String account, ArrayList<Object> roleIds, Long tenantId,
                        Long userId, Long companyId, Long orgId, String userName) {
        header.put("alg", "HS256");
        header.put("typ", "JWT");

        playLoad.put("code", code);
        playLoad.put("account", account);
        playLoad.put("roleIds", roleIds);
        playLoad.put("tenantId", tenantId);
        playLoad.put("companyId", companyId);
        playLoad.put("orgId", orgId);
        playLoad.put("userId", userId);
        playLoad.put("userName", userName);
        // 设置 过期时间
        playLoad.put("expiresAt",new Date(System.currentTimeMillis() + PERIOD));

        String json = header.toJSONString() + "." + playLoad.toJSONString();
        return signature(json);
    }

    /**
     * 签名算法
     * @param json 包含 header 和 payload
     * @return jwt token
     */
    private static String signature(String json) {
        return TokenUtil.encoderToken(json);
    }
}
